<template>
	<view>
		<u-toast ref="uToast"></u-toast>
		<u-navbar :placeholder="true" @leftClick="goBack" title="我的余额"></u-navbar>
		<view class="viewrr">
			<!-- 日期选择部分 -->
			<div class="time-slots-a">
				<scroll-view scroll-x="true" class="scroll-view-navbar" style="width: 100%">
					<view class="slot" v-for="notice in notices" :key="notice.id"
						:class="{ 'active': notice.id === currentNavItem }" @click="selectSlot(notice)">
						<view>{{ notice.weekDay }}</view>
						<view>{{ notice.monthDay }}</view>
					</view>
				</scroll-view>
			</div>

			<!-- 时间选择部分 -->
			<div class="time-slots-b">
				<view style="margin-bottom: 30rpx;">
					<TimeProgress :times="times" :current="currentTime" :pending-times="pendingTimes" />
				</view>
				<view class="flex align-center justify-between">
					<view class="flex align-center">
						<view class="flex align-center margin-right-xs">
							<view class="bg-blue" style="width: 15px;height: 15px;"></view>
							<text>不可预定时段</text>
						</view>
						<view class="flex margin-right-sm align-center">
							<view class="bg-tea" style="width: 15px;height: 15px;"></view>
							<text>可预定时段</text>
						</view>
						<view class="flex align-center">
							<view class="bg-red" style="width: 15px;height: 15px;"></view>
							<text>当前预定时段</text>
						</view>
					</view>
				</view>

				<view class="flex align-center">
					<view class="margin-top-lg">
						<view class="text-gray text-xs" style="margin-right: 40rpx;font-size: 14px;">预定时间:
							{{ changeTimeValue }}
						</view>
					</view>

					<!-- 时间选择器 -->
					<view class="flex align-center margin-top-lg">
						<view class="flex flex-direction align-center">
							<view class="textstart">
								<picker mode="time" :value="time" :start="timee" end="23:59" @change="bindTimeChange">
									<text class="text-tea text-xl" style="color: crimson;font-weight: bold;">{{ time }}
										<text style="font-weight: 100;margin-left: 4rpx;">设置</text></text>
								</picker>
							</view>
						</view>
						<view style="margin: 0 20rpx;">至</view>
						<view class="flex flex-direction align-center">
							<view class="textend">
								<text class="text-tea text-xl">{{ endTimeStr }}</text>
							</view>
						</view>
					</view>
				</view>
			</div>
		</view>
		<!-- 提示信息 -->
		<view class="textv">
			<view style="font-size: 12px;"><text
					style="margin-right: 5px;font-weight: bold;font-size: 16px;">选择套餐</text>温馨提示: 套餐只能在指定的日期、时间内使用
			</view>
			<view class="package-item" :class="{ active: selectedPackageId === packageq.id }"
				@click="selectPackage(packageq)" v-for="packageq in packages" :key="packageq.id">
				<view class="package-info">
					<view class="package-title">{{ packageq.pname }}</view>
					<text class="package-time">使用时段：<text class="text-bold text-black">00:00-次日00:00</text></text><br>
					<text class="package-validity">有效日期：<text class="text-bold text-black">周一至周日</text></text>
				</view>
				<view class="package-action">
					<text class="package-price">¥ {{ packageq.price }}</text>
				</view>
			</view>
			<view class="package-info" style="margin-top: 20px;">
				<view class="package-title" style="float: left;">团购券</view>
				<view style="float: right;">{{packagelistlength}} 张可用</view>
			</view>
		</view>

		<view style="padding-bottom: 100px;">
			<view v-for="(item, index) in packagelist" :key="item.id" class="margin-sm padding-sm bg-white radius">
				<view class="flex align-start justify-between" @click="confirmPayPackage(item)">
					<view>
						<view class="text-lg text-black text-bold">{{ item.yname }}</view>
						<view class="text-sm margin-top-sm">可用范围：{{ item.scope }}</view>
						<view class="text-sm">有效期至：{{ item.validity }}</view>
					</view>
					<view class="flex flex-direction" style="160rpx">
						<view class="text-tea text-lg">{{ item.price }}元</view>
						<view style="text-decoration: line-through;" class="text-sm">原价：{{ item.orginprice }}元
						</view>
						<view>
							<view class="gougou" :class="{'gou': item.id === isindex}">
								{{ item.id === isindex ? '√' : '' }}
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部预定信息 -->
		<view style="position: fixed;bottom: 0px;left: 0px;width: 100%;height: 120rpx;" class="bg-white">
			<view class="flex align-center justify-between margin-sm">
				<text class="text-lg text-bold" style="color: #F85B35;font-size: 18px;">￥{{ selectHours }}</text>
				<view>
					<!-- <button class="cu-btn bg-orange" style="width: 100px;" @click="submitYouhui">会员优惠</button> -->
					<button class="cu-btn bg-blue" style="width: 100px;" :disabled="isSubmitted"
						@click="submitOrder">确定下单</button>
				</view>
			</view>
		</view>
	</view>
</template>


<script>
	import {
		times
	} from '../../../uni_modules/uview-ui/libs/function/digit';
	import {
		getCouponByBid,
		getABoxMealByBid,
		addA,
		isUB
	} from '@/request/api_user.js';
	import {
		showToast
	} from '@/request/wx.js'
	import TimeProgress from '@/config/TimeProgress.vue';
	import code from '../../../uni_modules/uview-ui/libs/config/props/code';

	export default {
		components: {
			TimeProgress
		},
		data() {
			return {
				isindex: '',
				times: [], //显示时段数组
				currentTime: [], // 当前预定时段
				pendingTimes: [], // 不可预定时段
				packagelist: [], //优惠卷数组
				packagelistlength: '0',
				currentNavItem: '', // 当前选择的日期ID
				changeTimeValue: '', // 当前日期
				year: '', // 当前年
				time: '00:00', // 开始时间
				timee: '',
				endTimeStr: '- - -', //结束时间
				loadtime: '', //用来设置开始时间的
				selectHours: '0.0', //价格
				timeChangeForm: {
					NextDate: false,
					startTime: '',
					endTime: '',
					startTimeStr: '08:55', // 默认开始时间
					endTimeStr: '18:55' // 默认结束时间
				},
				notices: [],
				selectedPackageId: '', // 当前选中的套餐 ID
				isSelectedPackageId: '', //判断
				packages: [],
				order: {},
				isSubmitted: false, // 按钮点击状态
			};
		},
		onLoad(options) {
			let _storeid = uni.getStorageSync('storeid'); //门店ID
			console.log(parseInt(options.id));
			console.log(_storeid);

			this.order.shopid = _storeid;
			this.order.boxid = Number(options.id);
			this.setData();
			this.setLode(options.id);
			this.timee = this.time;
			this.currentNavItem = this.notices[0].id;
		},
		// onShow() {
		// 	console.log("sddsfds")

		// },
		methods: {
			goBack() {
				uni.navigateBack();
			},
			setLode(id) {
				// console.log("加载中")
				getABoxMealByBid({
					'bid': id
				}).then((req) => {
					console.log(req)
					this.packages = req.data.data;
				});

				getCouponByBid({
					'bid': id
				}).then((req) => {
					// console.log(req);
					if (req.data.code === 200) {
						this.packagelist = req.data.data;
						this.packagelistlength = req.data.data.length;
					} else {
						this.packagelistlength = 0;
					}
				});
			},
			getDate() {
				const today = new Date();
				const month = String(today.getMonth() + 1).padStart(2, "0");
				const day = String(today.getDate()).padStart(2, "0");
				return `${month}-${day}`;
			},
			getTime() {
				const today = new Date();
				const hours = String(today.getHours()).padStart(2, "0");
				const minutes = String(today.getMinutes()).padStart(2, "0");
				return `${hours}:${minutes}`;
			},
			getTimes() {
				const today = new Date();
				const todayHours = today.getHours();
				const currentHour = todayHours + Math.floor(today.getMinutes() / 60);

				const uuu = [];
				for (let i = 0; i < 24; i++) {
					const hour = (currentHour + i) % 24;
					uuu.push(hour);
				}
				// console.log(uuu);
				return uuu;
			},
			setData() { //获取日期
				// 获取今天日期，格式为 MM-DD
				const today = new Date();
				this.year = today.getFullYear();
				this.changeTimeValue = this.getDate();
				this.time = this.getTime();
				// 计算从今天开始往后7天的日期
				const daysArray = [];
				const weekDays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];

				for (let i = 0; i < 7; i++) {
					const date = new Date(today);
					date.setDate(today.getDate() + i); // 计算每一天的日期

					const id = i + 1; // 设置 ID，从 1 开始递增
					const year = date.getFullYear(); // 获取当前年份
					const weekDay = `${date.getMonth() + 1}-${String(date.getDate()).padStart(2, "0")}`; // 格式为 MM-DD
					const monthDay = weekDays[date.getDay()]; // 获取对应的中文星期几

					daysArray.push({
						id,
						weekDay,
						monthDay,
						year
					});
				}
				this.notices = daysArray;
				this.times = this.getTimes();
				// console.log(daysArray);
			},
			addHoursToTime(packageq, currentTime) {
				const [hours, minutes] = currentTime.split(":").map(Number); // 拆分时间为小时和分钟
				const newHours = hours + parseInt(packageq, 10); // 将小时数相加

				// 确保小时数在 24 小时制范围内（如需要，可以注释掉这一行）
				const formattedHours = newHours % 24;

				// 格式化时间，补零处理
				const finalTime = `${String(formattedHours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`;
				return finalTime;
			},
			setHoursToTime(packageq, currentTime) {
				let parts = currentTime.split(":");
				let hour = parseInt(parts[0], 10); // 将字符串转换为整数
				const hoursArray = [];
				for (let i = 0; i < packageq; i++) {
					let newHour = (hour + i) % 24; // 确保小时数在 0-23 范围内
					// 只有当新小时不在不可预定时段中时，才添加到数组中
					if (!this.pendingTimes.includes(newHour)) {
						hoursArray.push(newHour);
					} else {
						// 如果遇到不可预定的时段，可以在这里处理错误或者跳过
						// console.warn(`Hour ${newHour} is a pending time and will be skipped.`);
						return [];
					}
				}
				return hoursArray;
			},
			selectPackage(packageq) { // 选中套餐
				// 生成并设置当前预定时段的小时数组
				const result = this.setHoursToTime(packageq.val, this.time);
				// console.log(result.length)
				// 检查并报错如果当前时间数组为空
				if (result.length === 0) {
					// console.error('所选套餐的时段不可预定');
					showToast('该时间段不可用', 1500);
					// 可以在这里添加用户提示逻辑，例如使用 uni.showToast 显示错误信息
					return;
				}
				this.currentTime = result;
				this.isSelectedPackageId = 1;
				this.selectedPackageId = packageq.id;
				this.loadtime = packageq.val;
				this.selectHours = packageq.price;
				this.isindex = '';
				// 更新结束时间
				this.endTimeStr = this.addHoursToTime(packageq.val, this.time);
			},
			bindTimeChange(e) { //设置开始时间
				// 生成并设置当前预定时段的小时数组
				const result = this.setHoursToTime(this.loadtime, e.detail.value);
				// console.log(result.length);
				this.time = e.detail.value;
				if (this.loadtime === '') {
					return;
				}
				// 检查并报错如果当前时间数组为空
				if (result.length === 0) {
					showToast('该时间段不可用', 1500);
					// console.error('所选套餐的时段不可预定');
					// 可以在这里添加用户提示逻辑，例如使用 uni.showToast 显示错误信息
					return;
				}
				this.currentTime = result;
				// 更新结束时间
				this.endTimeStr = this.addHoursToTime(this.loadtime, e.detail.value);
			},
			selectSlot(notice) { // 选择日期
				this.currentNavItem = notice.id;
				this.changeTimeValue = notice.weekDay;
				this.year = notice.year;
				this.selectedPackageId = '';
				this.endTimeStr = '- - -';
				this.loadtime = '';
				this.currentTime = [];
				this.isindex = '';
				if (this.getDate() === notice.weekDay) {
					// console.log("今天");
					this.time = this.getTime();
					this.timee = this.getTime();
					this.times = this.getTimes();

				} else {
					// console.log("不是今天");
					this.times = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23];
					// 将pendingTimes转换成Set，以便进行快速查找
					const pendingSet = new Set(this.pendingTimes);

					// 使用find方法查找第一个不在pendingSet中的时间段
					const firstAvailableTime = this.times.find(time => !pendingSet.has(time));

					// console.log(firstAvailableTime); // 输出应该是0
					this.timee = firstAvailableTime < 10 ? '0' + firstAvailableTime + ':00' : firstAvailableTime + ':00';
					this.time = this.timee;
				}
			},
			submitOrder() { // 提交订单

				let name = '';
				if (this.isSelectedPackageId === 1) {
					name = this.packages.find(pkg => pkg.id === this.selectedPackageId)?.pname;
					// console.log(name);
				} else {
					name = this.packagelist.find(pkg => pkg.id === this.isindex)?.yname;
					// console.log(name);
				}
				console.log(name); //undefined需要判断
				if (name === undefined) {
					showToast('请选择套餐后在预定', 1500);
					return;
				}
				let user = uni.getStorageSync('UserInfo'); //用户ID
				console.log(user)
				if (!user) {
					console.log("用户还未登录");
					uni.showToast({
						title: '用户还未登录',
						icon: 'none', // 无图标
						duration: 1500, // 提示显示2秒后消失
						mask: true // 显示遮罩层
					});
					setTimeout(function() { // 延迟一定时间后执行页面跳转
						uni.navigateTo({
							url: `/pages/user/login/index`
						})
					}, 1500);
					return;
				}
				let year = this.year;
				let changeTimeValue = this.changeTimeValue;
				let daaa = `${year}-${changeTimeValue}`;
				// 示例使用
				const {
					formattedStartDate,
					formattedEndDate
				} = this.formatDateTime(daaa + ' ' + this.time, daaa + ' ' + this.endTimeStr);
				// console.log(`开始时间: ${formattedStartDate}`); // 开始时间: 2024-12-19 15:40
				// console.log(`结束时间: ${formattedEndDate}`); // 结束时间: 2024-12-19 19:40
				this.order.uid = user.id;
				this.order.pkgname = name;
				this.order.price = this.selectHours;
				this.order.starttimestr = formattedStartDate;
				this.order.endtimestr = formattedEndDate;

				if (!this.isSubmitted) {
					this.isSubmitted = true;
					console.log("订单已提交");
					uni.showLoading({
						title: "加载中",
						mask: true,
					});
					// 检查余额是否足够
					isUB({
							uid: user.id,
							price: this.selectHours
						}).then((ress) => {
							console.log(this.order)
						})
						.catch((error) => {
							console.error('检查余额失败', error);
						});
					addA({
						shopid: this.order.shopid,
						boxid: this.order.boxid,
						uid: user.id,
						pkgname: name,
						starttimestr: formattedStartDate,
						endtimestr: formattedEndDate,
						price: this.selectHours,
					}).then((resi) => {
						console.log('订单已提交', resi);
						uni.hideLoading();
						uni.switchTab({
							url: `/pages/user/index/myorder`
						})
					}).catch((error) => {
						console.error('添加订单失败', error);
					});
				}
			},
			padZero(num) { // 格式化日期时间字符串
				return num < 10 ? '0' + num : num;
			},
			formatDateTime(start, end) {
				// 将开始时间和结束时间转换为Date对象
				const startDate = new Date(start);
				const endDate = new Date(end);

				// 检查结束时间是否是第二天00:00或之后
				if (endDate.getHours() === 0 && endDate.getMinutes() === 0 && endDate.getSeconds() === 0) {
					// 如果结束时间是00:00，则日期加一天
					endDate.setDate(endDate.getDate() + 1);
				} else if (endDate < startDate) {
					// 如果结束时间小于开始时间，说明结束时间是第二天的时间
					endDate.setDate(endDate.getDate() + 1);
				}
				const format = (date) => {
					const year = date.getFullYear();
					const month = this.padZero(date.getMonth() + 1);
					const day = this.padZero(date.getDate());
					const hours = this.padZero(date.getHours());
					const minutes = this.padZero(date.getMinutes());
					return `${year}-${month}-${day} ${hours}:${minutes}`;
				};

				// 返回格式化的开始和结束时间
				return {
					formattedStartDate: format(startDate),
					formattedEndDate: format(endDate)
				};
			},
			confirmPayPackage(item) { //选择优惠卷
				// if (this.loadtime === '') {
				// 	// console.log("为空")
				// 	uni.showToast({
				// 		title: '还未选择套餐',
				// 		icon: 'none', // 无图标
				// 		duration: 1500, // 提示显示2秒后消失
				// 		// mask: true // 显示遮罩层
				// 	});
				// 	return;
				// }
				// if (this.loadtime === '' || this.loadtime != item.val) {
				// 	// console.log("优惠卷和套餐不符");
				// 	uni.showToast({
				// 		title: '优惠卷和套餐不符',
				// 		icon: 'none', // 无图标
				// 		duration: 1500, // 提示显示2秒后消失
				// 		// mask: true // 显示遮罩层
				// 	});
				// 	return;
				// }

				// 生成并设置当前预定时段的小时数组
				const result = this.setHoursToTime(item.val, this.time);
				// console.log(result.length)
				// 检查并报错如果当前时间数组为空
				if (result.length === 0) {
					showToast('该时间段不可用', 1500);
					// console.error('所选套餐的时段不可预定');
					// 可以在这里添加用户提示逻辑，例如使用 uni.showToast 显示错误信息
					return;
				}
				this.currentTime = result;
				// 更新结束时间
				this.endTimeStr = this.addHoursToTime(item.val, this.time);
				// console.log(item);
				// console.log(this.loadtime);
				this.isindex = item.id;
				this.selectedPackageId = ' ';
				this.isSelectedPackageId = '';
				this.loadtime = item.val;
				this.selectHours = item.price;
			},
		}
	}
</script>

<style>
	.gougou {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 40rpx;
		height: 40rpx;
		border-radius: 25px;
		border: 1px solid black;
	}

	.gou {
		font-size: 16px;
		font-weight: bold;
		color: white;
		background-color: blue;
	}

	.textend {
		background-color: #dfdfdf;
		color: #767676;
		width: 80px;
		height: 34px;
		border-radius: 25px;
		line-height: 34px;
		text-align: center;
	}

	.textstart {
		width: 110px;
		height: 36px;
		border-radius: 25px;
		line-height: 36px;
		text-align: center;
		border: 1px solid crimson;
	}

	.package-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px;
		margin-top: 10px;
		/* border: 1px solid #ddd; */
		border-radius: 8px;
		background-color: white;
	}

	.package-item.active {
		border: 1px solid blue;
		background: linear-gradient(to right, #ffffff, #85b6ff);
		/* background-color: #e6f7ff; */
	}

	/* .package-info {
		flex: 1;
	} */

	.package-title {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 5px;
	}

	.package-time,
	.package-validity {
		font-size: 12px;
		color: #666;
	}

	.package-action {
		display: flex;
		align-items: center;
	}

	.package-price {
		font-size: 18px;
		color: #f85b35;
		margin-right: 10px;
	}

	.quantity-control {
		display: flex;
		align-items: center;
	}

	.btn-decrease,
	.btn-increase {
		width: 30px;
		height: 30px;
		font-size: 18px;
		text-align: center;
		line-height: 30px;
		border: 1px solid #ccc;
		background-color: #fff;
		border-radius: 4px;
	}

	.btn-decrease:disabled {
		color: #ccc;
		border-color: #eee;
	}

	.quantity {
		font-size: 16px;
		margin: 0 10px;
	}

	.selected-icon {
		position: absolute;
		top: 10px;
		right: 10px;
		width: 24px;
		height: 24px;
		text-align: center;
		line-height: 24px;
		background-color: #007aff;
		color: #fff;
		border-radius: 50%;
	}

	.viewrr {
		position: fixed;
		top: 64px;
		left: 0px;
		z-index: 999;
		width: 100%;
	}

	.slsot {
		font-size: 14px;
		text-align: center;
		border: 1px solid #ddd;
		padding: 10px;
		border-radius: 8px;
		width: 90px;
		height: 80px;
	}

	.textv {
		margin-top: 235px;
		padding: 0 30rpx;
		padding-bottom: 26px;
	}

	.textv.tss {
		padding-bottom: 100px;
	}

	.scroll-view-navbar {
		white-space: nowrap;
	}

	.time-slots-a {
		padding: 15px 0px;
		border-bottom: 1px solid lightgrey;
		background-color: white;
	}

	.time-slots-b {
		padding: 10px;
		background-color: white;
		border-radius: 8px;
	}

	.slot {
		font-size: 14px;
		display: inline-block;
		margin-left: 10px;
		text-align: center;
		border: 1px solid #ddd;
		padding: 10px;
		border-radius: 8px;
		width: 90px;
		height: 80px;
	}

	.slot view {
		margin-top: 1px;
	}

	.slot view:last-child {
		margin-top: 14px;
	}

	.slot.active {
		background-color: blue;
		color: white;
	}

	.status {
		font-size: 13px;
	}
</style>